package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shops/models"
)

type ShopController struct {
	beego.Controller
}

// msg
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// add
func (c *ShopController) Add() {
	//接收数据
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	weight, _ := c.GetFloat("weight")
	number, _ := c.GetInt("number")
	end_time := c.GetString("end_time")

	if name == "" || price == 0 || weight == 0 || number == 0 || end_time == "" {
		res := Response{
			Code: 500,
			Msg:  "数据不能为空",
		}
		c.Data["josn"] = res
		c.ServeJSON()
		return
	}

	shop := models.Shops{
		Name:    name,
		Price:   price,
		Weight:  weight,
		Number:  number,
		EndTime: end_time,
	}
	err := models.DB.Debug().Create(&shop).Error
	if err != nil {
		res := Response{
			Code: 500,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	} else {
		res := Response{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
}

// list
func (c *ShopController) List() {
	var allshops []models.Shops
	err := models.DB.Debug().Find(&allshops).Error
	if err != nil {
		res := Response{
			Code: 500,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	} else {
		res := Response{
			Code: 200,
			Msg:  "查询成功",
			Data: allshops,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
}

// del
func (c *ShopController) Del() {
	//接收id
	id, _ := c.GetInt("id")
	shop := models.Shops{
		Id:         id,
		DeleteTime: "time.Now()",
	}
	err := models.DB.Debug().Updates(&shop).Error
	if err != nil {
		res := Response{
			Code: 500,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	} else {
		res := Response{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
}
